import { useState, useEffect, useRef } from 'react';
import { Link, Outlet, useNavigate } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth';
import { cn } from '@/lib/utils';

// 侧边栏项目类型定义
interface SidebarItem {
  label: string;
  path?: string;
  icon: string;
  children?: {
    label: string;
    path: string;
    icon: string;
  }[];
}

// 管理系统侧边栏导航项
const sidebarItems: SidebarItem[] = [
  { label: '仪表盘', path: '/admin', icon: 'fa-tachometer-alt' },
  { label: '轮播图管理', path: '/admin/banners', icon: 'fa-images' },
  {
    label: '内容中心',
    icon: 'fa-folder-open',
    children: [
      { label: '新闻动态', path: '/admin/news', icon: 'fa-newspaper' },
      { label: '公告公示', path: '/admin/announcements', icon: 'fa-bullhorn' },
      { label: '草稿箱', path: '/admin/drafts', icon: 'fa-file-lines' },
    ]
  },
  { label: '服务管理', path: '/admin/services', icon: 'fa-concierge-bell' },
  { label: '留言管理', path: '/admin/messages', icon: 'fa-envelope' },
  { label: '公司信息', path: '/admin/company-info', icon: 'fa-building' },
  { label: '联系信息', path: '/admin/contact-info', icon: 'fa-address-book' },
];

interface AdminLayoutProps {
  children: React.ReactNode;
}

export default function AdminLayout({ children }: AdminLayoutProps) {
  const [sidebarOpen, setSidebarOpen] = useState(true);
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const [expandedMenus, setExpandedMenus] = useState<string[]>(['内容中心']); // 默认展开内容中心
  const { isAuthenticated, logout, user } = useAuth();
  const navigate = useNavigate();
  const userMenuRef = useRef<HTMLDivElement>(null);
  
  const toggleSidebar = () => {
    setSidebarOpen(!sidebarOpen);
  };
  
  const handleLogout = () => {
    if (window.confirm('确定要退出登录吗？')) {
      logout();
      navigate('/admin/login');
    }
  };

  const toggleUserMenu = () => {
    setUserMenuOpen(!userMenuOpen);
  };

  const toggleSubmenu = (label: string) => {
    setExpandedMenus(prev =>
      prev.includes(label)
        ? prev.filter(item => item !== label)
        : [...prev, label]
    );
  };

  // 点击外部关闭用户菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (userMenuRef.current && !userMenuRef.current.contains(event.target as Node)) {
        setUserMenuOpen(false);
      }
    };

    if (userMenuOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [userMenuOpen]);
  
  return (
    <div className="flex h-screen bg-gray-100 overflow-hidden">
      {/* 侧边栏 */}
      <div 
        className={`bg-white shadow-md transition-all duration-300 ease-in-out ${
          sidebarOpen ? 'w-64' : 'w-20'
        } h-full fixed z-30`}
      >
        <div className="flex items-center justify-between p-4 border-b">
          <div className={`flex items-center ${!sidebarOpen && 'justify-center w-full'}`}>
            <div className="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center mr-3">
              <span className="text-white font-bold text-sm">EC</span>
            </div>
            {sidebarOpen && <span className="font-bold text-gray-800">管理系统</span>}
          </div>
          <button 
            onClick={toggleSidebar}
            className={`text-gray-500 hover:text-gray-700 ${!sidebarOpen && 'hidden'}`}
          >
            <i className="fa-solid fa-chevron-left"></i>
          </button>
        </div>
        
        <nav className="mt-5 px-2">
          {sidebarItems.map((item) => (
            <div key={item.label}>
              {item.children ? (
                // 有子菜单的项目
                <div>
                  <button
                    type="button"
                    onClick={() => toggleSubmenu(item.label)}
                    className="flex items-center justify-between w-full px-4 py-3 rounded-lg mb-1 text-gray-700 hover:bg-gray-100 transition-colors"
                  >
                    <div className="flex items-center">
                      <i className={`fa-solid ${item.icon} ${sidebarOpen ? 'mr-3' : 'mx-auto'}`}></i>
                      {sidebarOpen && <span>{item.label}</span>}
                    </div>
                    {sidebarOpen && (
                      <i className={`fa-solid fa-chevron-${expandedMenus.includes(item.label) ? 'down' : 'right'} text-sm`}></i>
                    )}
                  </button>

                  {/* 子菜单 */}
                  {sidebarOpen && expandedMenus.includes(item.label) && (
                    <div className="ml-4 space-y-1">
                      {item.children.map((child) => (
                        <Link
                          key={child.path}
                          to={child.path}
                          className={`flex items-center px-4 py-2 rounded-lg text-sm transition-colors ${
                            window.location.pathname === child.path
                              ? 'bg-blue-50 text-blue-600'
                              : 'text-gray-600 hover:bg-gray-50 hover:text-gray-900'
                          }`}
                        >
                          <i className={`fa-solid ${child.icon} mr-3`}></i>
                          <span>{child.label}</span>
                        </Link>
                      ))}
                    </div>
                  )}
                </div>
              ) : (
                // 没有子菜单的项目
                <Link
                  to={item.path!}
                  className={`flex items-center px-4 py-3 rounded-lg mb-1 transition-colors ${
                    window.location.pathname === item.path
                      ? 'bg-blue-50 text-blue-600'
                      : 'text-gray-700 hover:bg-gray-100'
                  }`}
                >
                  <i className={`fa-solid ${item.icon} ${sidebarOpen ? 'mr-3' : 'mx-auto'}`}></i>
                  {sidebarOpen && <span>{item.label}</span>}
                </Link>
              )}
            </div>
          ))}
          
          <div className="mt-8">
            <button
              onClick={handleLogout}
              className="flex items-center w-full px-4 py-3 rounded-lg mb-1 text-gray-700 hover:bg-gray-100 transition-colors"
            >
              <i className={`fa-solid fa-sign-out-alt ${sidebarOpen ? 'mr-3' : 'mx-auto'}`}></i>
              {sidebarOpen && <span>退出登录</span>}
            </button>
          </div>
        </nav>
      </div>
      
      {/* 主内容区 */}
      <div className={`transition-all duration-300 ease-in-out ${sidebarOpen ? 'ml-64' : 'ml-20'} flex-1 flex flex-col overflow-hidden`}>
        {/* 顶部导航 */}
        <header className="bg-white shadow-sm h-16 flex items-center justify-between px-6 sticky top-0 z-20">
          <button 
            onClick={toggleSidebar}
            className="text-gray-500 hover:text-gray-700 lg:hidden"
          >
            <i className="fa-solid fa-bars"></i>
          </button>
          
          <div className="flex items-center space-x-4">
            <div className="relative">
              <span className="absolute inset-y-0 left-0 flex items-center pl-3">
                <i className="fa-solid fa-search text-gray-400"></i>
              </span>
              <input
                type="text"
                placeholder="搜索..."
                className="bg-gray-100 text-sm rounded-lg pl-10 pr-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 w-64"
              />
            </div>
            
            <div className="relative">
              <button className="text-gray-500 hover:text-gray-700 relative">
                <i className="fa-solid fa-bell text-xl"></i>
                <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-4 h-4 flex items-center justify-center">3</span>
              </button>
            </div>
            
            <div className="relative" ref={userMenuRef}>
              <button
                onClick={toggleUserMenu}
                className="flex items-center space-x-2 text-gray-700 hover:text-gray-900 focus:outline-none"
              >
                <div className="w-8 h-8 rounded-full bg-gray-200 overflow-hidden">
                  <img
                    src="https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=admin+user+avatar%2C+professional+headshot%2C+neutral+background&sign=9276266fdca8484423a0b1aacae71e61"
                    alt="管理员头像"
                    className="w-full h-full object-cover"
                  />
                </div>
                <span className="ml-2 text-sm font-medium text-gray-700 hidden md:inline">{user?.username || '管理员'}</span>
                <i className="fa-solid fa-chevron-down text-xs text-gray-500"></i>
              </button>

              {/* 用户下拉菜单 */}
              {userMenuOpen && (
                <div className="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-50 border border-gray-200">
                  <div className="px-4 py-2 text-sm text-gray-700 border-b border-gray-100">
                    <div className="font-medium">{user?.username || '管理员'}</div>
                    <div className="text-gray-500">管理员</div>
                  </div>
                  <button
                    onClick={() => {
                      setUserMenuOpen(false);
                      // 这里可以添加个人设置页面的导航
                    }}
                    className="block w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
                  >
                    <i className="fa-solid fa-user mr-2"></i>
                    个人设置
                  </button>
                  <button
                    onClick={() => {
                      setUserMenuOpen(false);
                      handleLogout();
                    }}
                    className="block w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50"
                  >
                    <i className="fa-solid fa-sign-out-alt mr-2"></i>
                    退出登录
                  </button>
                </div>
              )}
            </div>
          </div>
        </header>
        
        {/* 页面内容 */}
        <main className="flex-1 overflow-y-auto p-6 bg-gray-50">
          {children}
        </main>
      </div>
    </div>
  );
}
